﻿using System;
using System.Windows.Browser;

namespace CRM.Tools.ODataQueryDesigner
{

    public static class ClientScript
    {
        /// <summary>
        /// Returns the ServerUrl from Microsoft Dynamics CRM
        /// </summary>
        /// <returns>String representing the ServerUrl or String.Empty if not found.</returns>
        public static string GetServerUrl()
        {
            //return "http://win2008x64:5555/XrmTools"; // for testing on local machine

            string urlPath = HtmlPage.Document.DocumentUri.LocalPath;
            string url = HtmlPage.Document.DocumentUri.ToString();

            string orgName = (string)GetContext().Invoke("getOrgUniqueName");
           
            int serverURlEnd = url.IndexOf("/", 8);
            if (serverURlEnd != -1 && url.ToLower().IndexOf(orgName.ToLower(), serverURlEnd) != -1)
            {
                // on premise
                url = url.Substring(0, url.IndexOf(urlPath) + 1);
                url += orgName;
            }
            else
            {
                // We are online
                url = (string)GetContext().Invoke("getServerUrl");
                if (url.EndsWith("/"))
                    url = url.Substring(0, url.Length - 1);
            }

            //if (url.IndexOf(".crm.dynamics.com") > 0 | url.IndexOf(".crm4.dynamics.com") > 0 | url.IndexOf(".crm5.dynamics.com") > 0)
            //{
            //    // We are online
            //    url = (string)GetContext().Invoke("getServerUrl");
            //    if (url.EndsWith("/"))
            //        url = url.Substring(0, url.Length - 1);
            //}
            //else
            //{
            //    // on premise
            //    string orgName = (string)GetContext().Invoke("getOrgUniqueName");
            //    url = url.Substring(0, url.IndexOf(urlPath) + 1);

            //    url += orgName + "/";
            //}



            //string serverUrl = (string)GetContext().Invoke("getServerUrl");
            //Remove the trailing forwards slash returned by CRM Online
            //So that it is always consistent with CRM On Premises
            //if (serverUrl.EndsWith("/"))
            //    serverUrl = serverUrl.Substring(0, serverUrl.Length - 1);



            return url;
        }
              


        private static ScriptObject GetContext()
        {
            ScriptObject xrmProperty = (ScriptObject)HtmlPage.Window.GetProperty("Xrm");
            if (null == xrmProperty)
            {
                //It may be that the global context should be used
                try
                {

                    ScriptObject globalContext = (ScriptObject)HtmlPage.Window.Invoke("GetGlobalContext");

                    return globalContext;
                }
                catch (System.InvalidOperationException)
                {
                    throw new InvalidOperationException("Property \"Xrm\" is null and the Global Context is not available.");
                }

            }

            ScriptObject pageProperty = (ScriptObject)xrmProperty.GetProperty("Page");
            if (null == pageProperty)
            {
                throw new InvalidOperationException("Property \"Xrm.Page\" is null");
            }

            ScriptObject contextProperty = (ScriptObject)pageProperty.GetProperty("context");
            if (null == contextProperty)
            {
                throw new InvalidOperationException("Property \"Xrm.Page.context\" is null");
            }

            return contextProperty;
        }
       

        /// <summary>
        /// Attempts to retrieve the Something from the html function GetSomething
        /// </summary>
        /// <returns></returns>
        //public static String GetSomething()
        //{
        //    try
        //    {
        //        return (String)HtmlPage.Window.Invoke("GetSomething");
        //    }
        //    catch
        //    {
        //        return null;
        //    }
        //}
    }
}
